extends Unit
class_name AllyBaseUnit


#region 属性配置

var max_hp: float = 1000.0
var hp: float = max_hp:
	set(value):
		if hp == value:
			return
		var _hp = clamp(value, 0, max_hp)
		GlobalSignal.gs_ally_hp_changed.emit(self, _hp, hp)
		hp = _hp
		if hp <= 0:
			_on_death()

# 基础战斗属性
var base_attack: float = 0.0
var defense_value: float = 0.0 # 数值减伤
var defense_percent_base: float = 25.0 # 百分比减伤基准值

# 元素抗性
var resistances: Dictionary = {
	GameConstant.DAMAGE_TYPE.FIRE: 0.0,
	GameConstant.DAMAGE_TYPE.LIGHTNING: 0.0,
	GameConstant.DAMAGE_TYPE.ICE: 0.0
}
#endregion

var damage_multiplier: float = 1.0

func _ready():
	hp = max_hp
	super ()
	
#region 伤害处理系统
func deal_damage(skill: Skill):
	"""处理造成伤害的全流程"""

	var base_damage: float
	# 创建伤害实例
	if skill.skill_type == GameConstant.SKILL_TYPE.ATTACK:
		base_damage = base_attack
	else:
		base_damage = skill.get_final_damage(self)
	var damage = Damage.new(
		base_damage,
		skill.damage_type,
		self
	)

	
	# 实际造成伤害
	if is_instance_valid(current_target):
		current_target.take_damage(skill, damage)
		
func take_damage(skill: Skill, damage: Damage):
	"""处理承受伤害的全流程"""
	if not is_alive():
		return
	# 应用抗性计算
	if damage.damage_type == GameConstant.DAMAGE_TYPE.PHYSICAL:
			# 计算防御减伤
		damage.base_value = _calculate_defense(damage.base_value)
	else:
		damage.base_value = _apply_resistance(damage)
	
	GlobalSignal.gs_ally_take_damage.emit(skill.caster, self, skill, damage)

	# 如果是致命伤害
	if damage.final_value >= hp:
		GlobalSignal.gs_ally_take_fatal_damage.emit(skill.caster, self, skill, damage)
	
	# 更新生命值
	hp -= damage.final_value

	
func _apply_resistance(damage: Damage) -> float:
	"""应用抗性计算公式：最终伤害 = 原始伤害 * (100 / (抗性值 + 100))"""
	# 获取对应伤害类型的抗性值，默认为0
	var resistance = resistances.get(damage.damage_type, 0.0)
	
	# 应用抗性公式（支持抗性值为0的情况）
	var mitigated_damage = damage.base_value * defense_percent_base / (resistance + defense_percent_base)
	
	# 确保最小伤害不低于1（可选配置）
	return max(mitigated_damage, 1.0)

func _calculate_defense(raw_damage: float) -> float:
	"""防御计算"""
	return raw_damage * defense_percent_base / (defense_value + defense_percent_base)
#endregion

#region 状态与事件
func is_alive() -> bool:
	return hp > 0

func _on_death():
	queue_free()
	GlobalSignal.emit_signal("gs_unit_died", self)

func _on_damage_taken(damage: float, source: Unit):
	GlobalSignal.emit_signal("gs_unit_damaged", self, damage, source)


func _update_navigation_target():
	if is_instance_valid(current_target):
		nav_agent.target_position = current_target.global_position
